package com.mm.common.interceptor;


import cn.hutool.core.util.StrUtil;
import com.mm.common.config.RedisProperties;
import com.mm.common.utils.SessionHolder;
import lombok.RequiredArgsConstructor;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.DispatcherServlet;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

/**
 * @BelongsProject: 6.hm-shop
 * @BelongsPackage: com.hmall.common.interceptor
 * @Author : 游在海里的鱼
 * @CreateTime : 2024-05-07  20:52
 * @Version : 1.0
 * @ClassName : TODO
 * @Description : TODO
 */
@Component
@RequiredArgsConstructor
@ConditionalOnClass(DispatcherServlet.class)
public class UserInfoInterceptor implements HandlerInterceptor {

    private final StringRedisTemplate stringRedisTemplate;
    private final RedisProperties redisProperties;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        stringRedisTemplate.opsForValue().set(redisProperties.session_user_pre+"123","2");
//        SessionHolder.saveUser(2L,"123");

        String token = request.getHeader("session-token");
        if(StrUtil.isNotBlank(token)){
            String uid = stringRedisTemplate.opsForValue().get(redisProperties.session_user_pre + token);
            SessionHolder.saveUser(Long.valueOf(uid),token);
            stringRedisTemplate.expire(token,redisProperties.session_user_save_time, TimeUnit.MINUTES);
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        SessionHolder.removeUser();
    }
}
